#include "main.h"
#include "stdio.h"
#include "adc.h"

#define ADC_SAMPLE_COUNT          1

static volatile uint16_t adc3_value[ADC_SAMPLE_COUNT][ADC_CHANNEL_COUNT];
static volatile int g_data_is_ok = 0;

extern ADC_HandleTypeDef hadc3;

int adc_init()
{
  return 0;
}

int get_adc_values(uint16_t *avg_value)
{
  uint32_t tick_start = HAL_GetTick();
  
  g_data_is_ok = 0;

  HAL_ADC_Start_DMA(&hadc3, (uint32_t*)adc3_value[0], ADC_CHANNEL_COUNT);
  while ((HAL_GetTick() - tick_start) < 50) {
    if (g_data_is_ok == 1) {
      break;
    }
  }
  if (g_data_is_ok == 1) {
#if 0
    uint16_t min_value[ADC_CHANNEL_COUNT] = { 0 };
    uint16_t max_value[ADC_CHANNEL_COUNT] = { 0 };
    int i = 0,j = 0;
    for (i = 0;i < ADC_CHANNEL_COUNT;i ++) {
      for (j = 0;j < ADC_SAMPLE_COUNT;j ++) {
        avg_value[i] += adc3_value[j][i];
        if (min_value[i] > adc3_value[j][i]) {
          min_value[i] = adc3_value[j][i];
        }
        if (max_value[i] < adc3_value[j][i]) {
          max_value[i] = adc3_value[j][i];
        }
      }
      avg_value[i] = (avg_value[i] - min_value[i] - max_value[i]) / (ADC_SAMPLE_COUNT - 1);
    }
#else
    avg_value[0] = adc3_value[0][0];
    avg_value[1] = adc3_value[0][1];
    avg_value[2] = adc3_value[0][2];
    avg_value[3] = adc3_value[0][3];
    avg_value[4] = adc3_value[0][4];
#endif
    //printf("ADC USE: %dms\n", HAL_GetTick() - tick_start);
    return 0;
  }
  return -1;
}

void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
{
  if (hadc == &hadc3) {
#if 0
    int i = 0;
    for (i = 0;i < ADC_SAMPLE_COUNT;i ++) {
      printf("%d. ADC: %d %d %d %d %d\n",i,
            adc3_value[i][0],adc3_value[i][1],
            adc3_value[i][2],adc3_value[i][3],
            adc3_value[i][4]);
    }
#endif
    g_data_is_ok = 1;
  }
}